<template>
  <div class="tab-detail-con">
    <div v-if="!selServiceInfo.id">
      <div class="top flex-c">
        <div style="flex: 1">
          <div class="service-provide-con">
            <div class="provider-item-con">
              <div @click="selProvider(item, index)" :class="['item', 'cursor', index == serviceProviderSelIndex ? 'active' : '']" v-for="(item, index) of serviceProviderList" :key="index">{{ item.companyShortName }}</div>
            </div>
          </div>
        </div>
        <div class="flex-c" style="width: 390px; justify-content: space-between">
          <a-select :style="{ width: '140px' }" @change="getProviderServiceItemList" v-model="taskType" allow-clear placeholder="请选择">
            <a-option value="NEW_PRODUCT_PICTURE" label="新品套图"></a-option>
            <a-option value="FIX_PICTURE" label="以图修图"></a-option>
            <a-option value="SHOOT_VIDEO" label="视频拍摄"></a-option>
            <a-option value="POSTER_SHOP_DESIGN" label="海报设计"></a-option>
            <a-option value="CHANGE_DIAMOND_COLOR" label="换钻调色"></a-option>
            <a-option value="HAND_DRAWN_DESIGN" label="手绘设计"></a-option>
          </a-select>
          <a-input-search :style="{ width: '240px' }" @search="getProviderServiceItemList" v-model="serContent" placeholder="请输入关键词"></a-input-search>
        </div>
      </div>
      <div class="flex-c mt5 mb5" style="color: #b57300">
        <div>当前服务商订单状态:</div>
        <div>待接单数:{{ countInfo.waitAcceptNum || 0 }};</div>
        <div>待执行数:{{ countInfo.waitScheduleNum || 0 }};</div>
        <div>执行中数:{{ countInfo.executingNum || 0 }};</div>
      </div>
      <div class="bottom">
        <div class="service-item-list-con mt10">
          <a-scrollbar style="height: 600px; overflow: auto" v-loading="serviceItemLoading">
            <div class="service-goods-con">
              <div class="service-goods mr10 mb10" v-if="serviceItemList.length > 0" v-for="(item, index) of serviceItemList" :key="index" @click="showServiceDetail(item)">
                <div class="top clearfix">
                  <div class="fl ser-Content">
                    <TextLimit :val="item.serContent" :rows="1" position="top"></TextLimit>
                  </div>
                  <div class="fr common-text">{{ taskTypeMap[$extract(item, 'taskConfig.taskType')] }}</div>
                </div>

                <div class="mt10" v-if="item.taskConfig.taskType == 'NEW_PRODUCT_PICTURE'">
                  <span class="common-text left-text">原图来源：</span>
                  <span>{{ originPicSourceMap[item.originPicSource] }}</span>
                  <span class="sample-con" v-if="item.isSample">样</span>
                </div>

                <div class="mt10" v-if="item.taskConfig.taskType == 'SHOOT_VIDEO'">
                  <span class="common-text left-text">拍摄方式：</span>
                  <span>{{ shootTypeMap[item.shootType] }}</span>
                  <span class="sample-con" v-if="item.isSample">样</span>
                </div>

                <div class="mt10">
                  <a-space>
                    <span class="common-text left-text">交付内容：</span>
                    <div style="flex: 1">
                      <textLimit :rows="1" position="top" :val="deliveryData(item.taskNodeList)"></textLimit>
                    </div>
                  </a-space>
                </div>
                <div class="mt10">
                  <span class="common-text left-text">执行周期：</span>
                  <span>{{ item.executeCycle }}天</span>
                </div>
                <div class="mt10">
                  <span class="common-text left-text">预计交付日期：</span>
                  <span>{{ $setTime(item.gmtPlanDelivery, 'YYYY-MM-DD') }}</span>
                </div>
                <div class="clearfix footer" style="margin-top: 20px">
                  <div class="fl" style="width: 210px">
                    <span class="common-text">报价：</span>
                    <span
                      ><span style="color: red; font-size: 16px">￥{{ item.amtQuote }}</span
                      >/单</span
                    >
                  </div>
                  <div class="fr">
                    <a-button size="mini" shape="round" type="primary" @click.stop="selService(item)">选购</a-button>
                  </div>
                </div>
              </div>
              <a-empty v-else />
            </div>
          </a-scrollbar>
        </div>
      </div>
    </div>

    <a-scrollbar v-else style="height: 650px; overflow: auto">
      <div class="clearfix" style="min-height: 650px">
        <div class="fl sel-item-detail left">
          <div class="service-title flex-c">
            <div class="text-limit" style="flex: 1; font-size: 18px; font-weight: 700">
              <textLimit position="top" :rows="1" :val="selServiceInfo.serContent"></textLimit>
            </div>
            <div style="width: 120px; text-align: right">{{ taskTypeMap[selServiceInfo.taskConfig.taskType] }}</div>
          </div>
          <div class="service-price mt20">
            <span style="color: red; font-size: 20px; font-weight: 700">￥{{ selServiceInfo.amtQuote }}</span>
            <span>/单</span>
          </div>
          <!-- 服务商信息 -->
          <div class="flex-c service-com-short-description mt20">
            <div class="img" style="width: 20px; height: 20px">
              <img src="https://cdn2.selleroa.com/yfni/test/170953244263872abd3.png" alt="" />
            </div>
            <div class="ml5" style="color: #644200; font-weight: 700"> 服务商：{{ serviceProviderInfo.companyShortName }} </div>
            <div class="ml5 line"></div>
            <div class="ml5 base-text-color">待接单数：{{ countInfo.waitAcceptNum || 0 }}</div>
            <div class="ml5 base-text-color">待执行数：{{ countInfo.waitScheduleNum || 0 }}</div>
            <div class="ml5 base-text-color">执行中数：{{ countInfo.executingNum || 0 }}</div>
          </div>
          <!-- 基本信息 -->
          <div class="basic-info mt20">
            <div class="h1" style="font-size: 16px; font-weight: 700">基本信息</div>
            <div class="mt10" v-if="selTaskType == 'NEW_PRODUCT_PICTURE'">
              <span class="current-page-common-text">原图来源：</span>
              <span>{{ originPicSourceMap[selServiceInfo.originPicSource] }}</span>
              <span class="sample-con" v-if="selServiceInfo.isSample">样</span>
            </div>
            <div class="mt10" v-if="selTaskType == 'SHOOT_VIDEO'">
              <span class="current-page-common-text">拍摄方式：</span>
              <span>{{ shootTypeMap[selServiceInfo.shootType] }}</span>
            </div>
            <div class="mt10">
              <span class="current-page-common-text">交付内容：</span>
              <span>{{ deliveryData(selServiceInfo.taskNodeList) }}</span>
            </div>
            <div class="mt10">
              <span class="current-page-common-text">执行周期：</span>
              <span> {{ selServiceInfo.executeCycle }} 天</span>
            </div>
            <div class="mt10">
              <span class="current-page-common-text">预计交付日期：</span>
              <span>{{ $setTime(selServiceInfo.gmtPlanDelivery) }}</span>
            </div>
          </div>
          <!-- 送样信息 -->
          <div class="sample-address mt20" v-if="selServiceInfo.isSample">
            <div class="flex-c">
              <div style="font-size: 16px; font-weight: 700">送样信息</div>
              <div class="ml10 common-text">送样之后请及时提交送样情况</div>
              <div style="flex: 1; text-align: right">
                <a-button class="copy-handle-btn" type="text" @click="copy(serviceProviderInfo)">复制地址</a-button>
              </div>
            </div>
            <div class="address-con">
              <div class="address flex" v-if="$extract(serviceProviderInfo, 'taskConfig.sampleAddress.userName')">
                <div class="flex-c-c" style="width: 40px; text-align: center">
                  <img style="width: 20px" src="https://cdn2.selleroa.com/yfni/test/1709540781020ab5050.png" alt="" />
                </div>
                <div style="flex: 1">
                  <div>{{ $extract(serviceProviderInfo, 'taskConfig.sampleAddress.userName') }}（{{ $extract(serviceProviderInfo, 'taskConfig.sampleAddress.phone') }}）</div>
                  <div>{{ $extract(serviceProviderInfo, 'taskConfig.sampleAddress.stateOrRegion') }}，{{ $extract(serviceProviderInfo, 'taskConfig.sampleAddress.city') }}，{{ $extract(serviceProviderInfo, 'taskConfig.sampleAddress.address') }}</div>
                </div>
              </div>
              <div v-else style="text-align: center">
                <div>暂无送样地址信息</div>
              </div>
            </div>
          </div>
          <!-- 产品原图 -->
          <div class="mt20" v-if="(selTaskType == 'NEW_PRODUCT_PICTURE' && selServiceInfo.originPicSource == 'APARTY_PROVIDE') || selTaskType == 'CHANGE_DIAMOND_COLOR'">
            <div class="mt20">
              <span style="font-size: 16px; font-weight: 700">原始图片</span>
              <span class="common-text ml5">产品原图是修产品橱窗图的基础</span>
              <span class="cursor highlight fs12 ml10" style="font-weight: 200" @click="showGetSkuImgModal = true">获取已有SKU的产品图</span>
            </div>
            <div class="product-img-box">
              <div class="box">
                <a-image-preview-group infinite>
                  <div class="box-img-con" style="position: relative" v-for="(item, index) of originalPicList" :key="index">
                    <div style="width: 100%; position: absolute; bottom: 0; left: 0; text-align: center; background: rgba(0, 0, 0, 0.5); z-index: 1">
                      <icon-delete style="color: white" class="cursor" @click="originalPicList.splice(index, 1)" />
                    </div>
                    <a-image :src="'https://erpapi.selleroa.com/v1/aliyun/oss/getAmazonImage?url=' + item.url" width="100%" height="100%" />
                  </div>
                  <div class="fl" style="width: 80px; height: 80px">
                    <a-upload class="fl" v-loading="uplaodfixPicLoading" :show-file-list="false" list-type="picture-card" action="/" :on-before-upload="(file) => uploadBefore(file, 'originalPic')" />
                  </div>
                </a-image-preview-group>
              </div>
            </div>
          </div>
          <!-- CAD文件 -->
          <div class="mt20" v-if="(selTaskType == 'NEW_PRODUCT_PICTURE' && selServiceInfo.originPicSource == 'C4D_RENDER') || (selTaskType == 'SHOOT_VIDEO' && selServiceInfo.shootType == 'RENDER_SHOOT')">
            <div>
              <span style="font-size: 16px; font-weight: 700">CAD文件</span>
              <span class="ml5 common-text">渲染需要有产品CAD文件</span>
              <span class="cursor highlight ml10 fs12" style="font-weight: 200" @click="getListForSkuInfo('CAD')">从产品上获取CAD</span>
            </div>
            <div>
              <a-upload action="/" @before-upload="(file) => uploadBefore(file, 'cad')">
                <template #upload-button>
                  <a-button type="primary" :loading="uplaodfixPicLoading">上传文件</a-button>
                </template>
              </a-upload>
            </div>
            <div class="att-list-con">
              <div class="att-item clearfix" v-for="(item, index) of cadList" :key="index">
                <div class="fl">{{ item.name }}</div>
                <div style="margin-right: 5px" class="fr cursor" @click="cadList.splice(index, 1)"><icon-close /></div>
              </div>
            </div>
          </div>
          <!-- 任务样片 -->
          <div class="mt20" v-if="selTaskType == 'SHOOT_VIDEO'">
            <div style="font-size: 16px; font-weight: 700">任务样片</div>
            <div>
              <a-radio-group v-model="videoUrl" @change="changeVideo">
                <div class="sel-template">
                  <div class="item" v-for="(item, index) in VideoList" :key="index">
                    <div class="top">
                      <video :src="item.url" style="width: 180px; height: 100px" width="160" height="160" controls></video>
                    </div>
                    <div class="bottom">
                      <a-radio :value="item.url">样品{{ index + 1 }}</a-radio>
                    </div>
                  </div>
                </div>
              </a-radio-group>
            </div>
          </div>
        </div>
        <div class="fl sel-item-detail right">
          <!-- 账户余额 -->
          <div class="flex-c">
            <div class="img" style="width: 40px; height: 40px">
              <img src="https://cdn2.selleroa.com/yfni/test/1709531834135c8924b.png" alt="" />
            </div>
            <div class="ml10">
              <span class="fl" style="height: 28px; line-height: 28px; color: #6a4017">{{ $extract(walletInfo, 'consumeWalletAccount.userName') }}可用余额：</span>
              <span class="fl" style="color: red; font-size: 20px; color: #643910">￥{{ price }}</span>
            </div>
          </div>
          <!-- 选择执行人 -->
          <div class="mt10">
            <a-space>
              <div class="required">任务雇主：</div>
              <a-select @change="changeUser" v-model="form.employer.id" style="width: 240px" placeholder="请选择" allow-search>
                <a-option :value="item.id" :label="item.name" v-for="(item, index) of userList" :key="index"></a-option>
              </a-select>
            </a-space>
            <div class="mt5" style="color: #bb7e00">
              <a-space>
                <div>
                  <span>创建人：</span>
                  <span>{{ userInfo.userName }}</span>
                </div>
                <div>
                  <span>验收人：</span>
                  <span>{{ form.verifyerList.map((e: any) => e.name).join(',') }}</span>
                </div>
              </a-space>
            </div>

            <div class="common-text mt5">雇主才是任务的真实所属任务,多个验收人只需其中1人验收即可</div>
          </div>
          <!-- 关联产品SKU -->
          <div>
            <div class="mt20">
              <span :class="[selTaskType == 'NEW_PRODUCT_PICTURE' ? 'required' : '']">关联产品SKU：</span>
              <span class="common-text">如果关联产品SKU则将任务交付物上传到产品SKU的资料库。</span>
            </div>
            <div class="sku-info">
              <a-select v-if="!skuInfo.id" :style="{ width: '180px' }" @change="handleChangeSku" :loading="searchSkuLoading" placeholder="请输入sku" @search="handleSearch" allow-clear allow-search :filter-option="false" :show-extra-options="false">
                <a-option v-for="(item, index) of skuOption" :key="index" :label="item.sku" :value="item.sku"></a-option>
              </a-select>
              <div class="clearfix sku-detail-con" style="font-size: 12px" v-else>
                <div class="fl">
                  <ImgPopover :src="imgUrl(skuInfo)">
                    <template #con>
                      <a-image :preview="false" width="60" height="60" fit="contain" :src="imgUrl(skuInfo)" />
                    </template>
                  </ImgPopover>
                </div>
                <div class="fl" style="width: 400px; margin: 10px 10px 0 10px">
                  <a-space>
                    <span class="common-text">名称：</span>
                    <div style="width: 350px">
                      <TextLimit position="top" :rows="1" :val="skuInfo.skuName"></TextLimit>
                    </div>
                  </a-space>
                  <div style="margin-top: 5px">
                    <span class="common-text">SKU：</span>
                    <span>{{ skuInfo.sku }}</span>
                    <span class="common-text" style="margin-left: 20px">SPU/类目:</span>
                    <span v-if="props.type == 'add'">{{ $extract(skuInfo, 'productSpu.spu') }}/{{ $extract(skuInfo, 'productSpu.category.name') }}</span>
                    <span v-else>{{ $extract(skuInfo, 'spu') }}/{{ $extract(skuInfo, 'category.name') }}</span>
                  </div>
                </div>

                <div class="del-btn highlight cursor" @click="skuInfo = {}">
                  <icon-delete style="font-size: 20px" />
                </div>
              </div>
            </div>
          </div>
          <!-- 任务要求 -->
          <div>
            <div class="mt20">任务要求</div>
            <a-textarea v-model="demand" placeholder="请输入任务要求" allow-clear />
          </div>
          <!-- 任务附件 -->
          <div>
            <div class="mt20">
              <a-space>
                <div>任务附件</div>
                <div class="common-text">如果还有其他跟任务相关的资料就在此上传相关任务</div>
              </a-space>
            </div>
            <div>
              <a-upload action="/" @before-upload="(file) => uploadBefore(file, 'att')">
                <template #upload-button>
                  <a-button type="text" :loading="attUplaodfixPicLoading">
                    <template #icon>
                      <icon-attachment />
                    </template>
                    <template #default>选择附件</template>
                  </a-button>
                </template>
              </a-upload>
            </div>
            <div class="att-list-con">
              <div class="att-item clearfix" v-for="(item, index) of attList" :key="index">
                <div class="fl">{{ item.name }}</div>
                <div style="margin-right: 5px" class="fr cursor" @click="attList.splice(index, 1)"><icon-close /></div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </a-scrollbar>
  </div>
  <getSkuImg v-model:model-value="showGetSkuImgModal" v-if="showGetSkuImgModal" @save="saveSkuImg" />
  <serviceDetail v-if="showServiceDetailModal" v-model="showServiceDetailModal" :deliveryData="deliveryData" :statics="countInfo" :serviceInfo="serviceInfo" :companyInfo="serviceProviderInfo" />
  <!-- <a-image-preview-group v-model:visible="visible" v-model:current="current" infinite :srcList="originalPicList.map((e:any) => e.url)" /> -->
</template>

<script lang="ts" setup>
  import serviceDetail from './serviceDetail.vue'
  import { defineComponent, ref, onMounted } from 'vue'
  import { deliveryMap, originPicSourceMap, shootTypeMap, taskTypeMap } from './map'
  import { OSSUpload } from '@/utils/ossUpload'
  import { getSkuDetailBySku } from '@/api/product'
  import { getOrganizesUser } from '@/api/system'
  import { listFuzzyBySku, countTaskStatusByTakeCompanyId, listTakeCompanysByTaskTypev2, listTaskServiceByCompanyId, getTaskById } from '@/api/task'
  import { Message } from '@arco-design/web-vue'
  import useClipboard from 'vue-clipboard3'
  import useUserStore from '@/store/modules/user'
  import getSkuImg from './getSkuImg.vue'
  import _ from 'lodash-es'
  const props = defineProps(['showFooter', 'price', 'walletInfo', 'type', 'info'])
  const { toClipboard } = useClipboard()
  const userInfo = useUserStore()
  let taskType = ref('')
  let serContent = ref('')
  let selTaskType = ref('')
  let demand = ref('')
  let serviceProviderSelIndex = ref(0) //选中的服务商索引
  let serviceProviderList = ref([]) //服务商列表
  let serviceProviderInfo: any = ref({}) //选中的服务商信息
  let countInfo: any = ref({}) //选中公司的订单情况
  let serviceItemList: any = ref([]) //服务商下的服务列表
  let serviceInfo: any = ref({}) //服务详情
  let showServiceDetailModal: any = ref(false)
  let serviceItemLoading: any = ref(false)
  let uplaodfixPicLoading: any = ref(false)
  let attUplaodfixPicLoading: any = ref(false)
  let searchSkuLoading: any = ref(false)
  let showGetSkuImgModal: any = ref(false)
  let visible: any = ref(false)
  let current: any = ref(0)
  let selServiceInfo: any = ref({})
  let originalPicList: any = ref([]) // 产品原图
  let VideoList: any = ref([]) // 视频样片
  let videoUrl: any = ref([]) // 选中的视频样片URL
  let videoObj: any = ref({}) // 选中的样片对象
  let cadList: any = ref([]) // CAD列表
  let userList: any = ref([]) // 任务验收人列表
  let skuInfo: any = ref({}) // 任务验收人列表
  let skuOption: any = ref([]) // 任务验收人列表
  let detailInfo = ref({})
  let form: any = ref({
    employer: {},
    verifyerList: [],
  })
  let attList = ref([]) // 任务附件
  // 选择服务商
  const selProvider = (data: any, index: number) => {
    serContent.value = ''
    taskType.value = ''
    serviceProviderSelIndex.value = index
    serviceProviderInfo.value = data
    getProviderOrderCount()
    getProviderServiceItemList()
  }
  // 获取服务商
  const getServiceProviderList = async () => {
    let params = {
      companyId: userInfo.companyId,
      taskTypeList: ['NEW_PRODUCT_PICTURE', 'FIX_PICTURE', 'SHOOT_VIDEO', 'POSTER_SHOP_DESIGN', 'CHANGE_DIAMOND_COLOR', 'HAND_DRAWN_DESIGN'],
    }
    const res: any = await listTakeCompanysByTaskTypev2(params)
    serviceProviderList.value = res?.data || []
    if (props.type != 'add') {
      let index = serviceProviderList.value.findIndex((e: any) => e.companyId == detailInfo.value.takeCompany.id)
      serviceProviderSelIndex.value = index
      serviceProviderInfo.value = serviceProviderList.value[index] || {}
    } else {
      serviceProviderInfo.value = serviceProviderList.value[0] || {}
    }

    getProviderOrderCount()
    getProviderServiceItemList()
  }
  // 获取当前选中的服务商的订单情况
  const getProviderOrderCount = async () => {
    let params = {
      takeCompanyId: serviceProviderInfo.value.companyId,
    }
    const res: any = await countTaskStatusByTakeCompanyId(params)
    countInfo.value = res?.data || {}
  }
  // 服务商的服务列表
  const getProviderServiceItemList = async () => {
    let params = {
      companyId: serviceProviderInfo.value.companyId,
      serContent: serContent.value,
      taskType: taskType.value,
    }
    serviceItemLoading.value = true
    const res: any = await listTaskServiceByCompanyId(params)
    serviceItemLoading.value = false
    serviceItemList.value = res?.data || []
  }
  // 查看服务详情
  const showServiceDetail = (data: any) => {
    serviceInfo.value = data
    showServiceDetailModal.value = true
  }
  // 处理任务内容
  const deliveryData = (list: any) => {
    let arr = list.reduce((pre: any, cur: any) => {
      return (pre = [...pre, ...cur.taskContentList])
    }, [])
    return arr
      .filter((ell: any) => ell.quantity && ell.quantity > 0)
      .map((e: any) => `${deliveryMap[e.contentType]}×${e.quantity}`)
      .join(',')
  }
  // 选择服务信息
  const selService = (data: any) => {
    serviceProviderInfo.value = {
      ...serviceProviderInfo.value,
      taskConfig: data.taskConfig,
    }
    selTaskType.value = data.taskConfig.taskType
    // attList.value = []
    // originalPicList.value = []
    // cadList.value = []
    // demand.value = ''
    VideoList.value = serviceProviderInfo.value.taskConfig?.sampleVideoList || []
    selServiceInfo.value = data

    console.log(selTaskType.value, selServiceInfo.value)

    props.showFooter(data)
  }

  // 清空服务信息
  const resetServiceInfo = () => {
    selServiceInfo.value = {}
  }

  const copy = async (data: any) => {
    try {
      let str = `${data.taskConfig.sampleAddress.userName}-${data.taskConfig.sampleAddress.phone}
  ${data.taskConfig.sampleAddress.stateOrRegion}-${data.taskConfig.sampleAddress.city}-${data.taskConfig.sampleAddress.address}`
      // 复制
      await toClipboard(str)
      Message.success('复制成功')
      // 复制成功
    } catch (e) {
      // 复制失败
    }
  }

  const showImgPre = (index: number) => {
    current.value = index
    visible.value = true
  }

  // 上传附件
  const uploadBefore: any = async (file: File, type: string) => {
    type != 'att' ? (uplaodfixPicLoading.value = true) : (attUplaodfixPicLoading.value = true)
    const res: any = await OSSUpload(file)
    uplaodfixPicLoading.value = false
    attUplaodfixPicLoading.value = false
    if (res) {
      let obj = {
        url: res.url,
        name: res.name.split('/')[res.name.split('/').length - 1],
      }
      if (type == 'att') {
        attList.value.push(obj)
      } else if (type == 'cad') {
        cadList.value.push(obj)
      } else {
        originalPicList.value.push(obj)
      }
    }
  }

  // 选中样片
  const changeVideo = (url: string) => {
    console.log(url)
    let item = VideoList.value.find((e: any) => e.url == url)
    videoObj.value = item
  }

  const getUserList = async () => {
    let params = {
      depart: false,
      pageNum: 1,
      pageSize: 1000,
    }
    const res: any = await getOrganizesUser(params)
    userList.value = res.data.records.map((e: any) => {
      e.name = e.userName
      return e
    })
  }

  const setEmployer = () => {
    let obj = {
      id: userInfo.userId,
      name: userInfo.userName,
    }
    form.value.employer = _.cloneDeep(obj)
    form.value.verifyerList.push(_.cloneDeep(obj))
  }

  const changeUser: any = (val: string) => {
    let item: any = userList.value.find((item: any) => item.id == val)
    if (item) {
      form.value.employer.id = item.id
      form.value.employer.name = item.name

      if (form.value.verifyerList[0].id != item.id) {
        let obj = {
          id: item.id,
          name: item.name,
        }
        form.value.verifyerList.splice(1, 1, obj)
      } else {
        form.value.verifyerList.splice(1, 1)
      }
    }
  }

  const handleSearch = async (value: string) => {
    if (value) {
      try {
        searchSkuLoading.value = true
        const res: any = await listFuzzyBySku({ sku: value })
        skuOption.value = res.data || []
      } catch (error) {}
      searchSkuLoading.value = false
    } else {
      skuOption.value = []
    }
  }

  const handleChangeSku: any = async (value: string) => {
    const res: any = await getSkuDetailBySku(value)
    skuInfo.value = res.data || {}
  }

  const imgUrl = (data: any) => {
    return (data?.productPicList && data?.productPicList[0]?.url) || ''
  }

  const saveSkuImg = (list: any) => {
    list.forEach((e: any) => {
      let obj = {
        url: e,
        name: e,
      }
      originalPicList.value.push(obj)
    })
  }

  // 通过SKU获取cad文件
  const getListForSkuInfo = (skuType: String) => {
    if (!skuInfo.value.id) {
      return Message.error('请选择sku')
    }
    let arr = skuInfo.value.productSpu?.productInfoList || []
    if (skuType == 'CAD') {
      let cadArr: any = arr.filter((e: any) => e.type == skuType)
      if (!cadArr[0]) return Message.error('产品上没有CAD文件')
      cadList.value = [...cadList.value, ...cadArr]
    } else {
      let originalPicArr = arr.filter((e: any) => e.type == skuType)
      if (!originalPicArr[0]) return Message.error('产品上没有原图文件')
      originalPicList.value = [...originalPicList.value, ...arr.filter((e: any) => e.type == skuType)]
    }
  }

  const getForm = () => {
    let params: any = {
      takeCompany: {
        id: serviceProviderInfo.value.companyId,
        companyShortName: serviceProviderInfo.value.companyShortName,
      },
    }
    if (selTaskType.value == 'NEW_PRODUCT_PICTURE' && !skuInfo.value.id) {
      Message.error('请选择sku')
      return false
    }

    if (selTaskType.value == 'NEW_PRODUCT_PICTURE' && selServiceInfo.value.originPicSource == 'C4D_RENDER' && !cadList.value[0]) {
      Message.error('请上传CAD文件')
      return false
    }

    if (selTaskType.value == 'NEW_PRODUCT_PICTURE' && selServiceInfo.value.originPicSource == 'APARTY_PROVIDE' && !originalPicList.value[0]) {
      Message.error('请上传原图')
      return false
    }

    if (skuInfo.value.id) {
      let arr = skuInfo.value.productSpu?.productInfoList || []
      let obj = {
        id: skuInfo.value.id,
        cadList: props.type == 'add' ? arr.filter((e: any) => e.type == 'CAD') : skuInfo.value.cadList,
        category: props.type == 'add' ? skuInfo.value.productSpu?.category || {} : skuInfo.value.category,
        developer: props.type == 'add' ? skuInfo.value.productSpu?.developer || {} : skuInfo.value.developer,
        handDrawList: props.type == 'add' ? arr.filter((e: any) => e.type == '手绘稿') : skuInfo.value.handDrawList,
        originPicList: props.type == 'add' ? arr.filter((e: any) => e.type == '原图') : skuInfo.value.originPicList,
        productPicList: skuInfo.value.productPicList || [],
        sku: skuInfo.value.sku,
        skuName: skuInfo.value.skuName,
        spu: props.type == 'add' ? skuInfo.value.productSpu?.spu : skuInfo.value.spu,
        spuName: props.type == 'add' ? skuInfo.value.productSpu?.spuName : skuInfo.value.spuName,
      }
      params.product = obj
    }

    let taskRequire: any = {
      id: selServiceInfo.value.id,
      isSample: selServiceInfo.value.isSample,
      amtQuote: selServiceInfo.value.amtQuote,
      attachmentList: attList.value || [],
      cadList: cadList.value || [],
      originPicList: originalPicList.value || [],
      demand: demand.value,
      executeCycle: selServiceInfo.value?.executeCycle,
      serContent: selServiceInfo.value?.serContent,
      serDesc: selServiceInfo.value?.serDesc,
      serShortId: selServiceInfo.value?.serShortId,
      taskNodeList: selServiceInfo.value?.taskNodeList,
    }
    // 样片
    if (selTaskType.value == 'SHOOT_VIDEO' && videoObj.value.url) {
      taskRequire.sampleVideoList = [videoObj.value]
    }
    // 送样地址
    if (selServiceInfo.value.isSample) {
      params.sendSample = {}
      params.sendSample.sampleAddress = serviceProviderInfo.value.taskConfig?.sampleAddress
    }

    if (selTaskType.value == 'NEW_PRODUCT_PICTURE') {
      taskRequire.originPicSource = selServiceInfo.value.originPicSource
    }
    if (selTaskType.value == 'SHOOT_VIDEO') {
      taskRequire.shootType = selServiceInfo.value.shootType
    }
    params.taskRequire = taskRequire
    if (props.type != 'add') params.id = detailInfo.value.id

    return { ...params, ...form.value, type: selTaskType.value }
  }

  const setInfo = async (data: any) => {
    console.log(serviceItemList.value, serviceProviderList.value)

    await getProviderOrderCount()
    await getProviderServiceItemList()
    let item = serviceItemList.value.find((e: any) => e.id == data.taskRequire?.id)
    if (item) {
      selServiceInfo.value = item
      selTaskType.value = item.taskConfig.taskType
    }
    VideoList.value = serviceProviderInfo.value.taskConfig?.sampleVideoList || []
    // 回填选中的服务信息
    attList.value = data?.taskRequire?.attachmentList || []
    cadList.value = data?.taskRequire?.cadList || []
    originalPicList.value = data?.taskRequire?.originPicList || []
    demand.value = data?.taskRequire?.demand || ''
    skuInfo.value = data?.product || {}
    // 是否选了样片
    let videoInfo = data?.taskRequire?.sampleVideoList ? data?.taskRequire?.sampleVideoList[0] : {}
    videoUrl.value = videoInfo.url || ''
    videoObj.value = videoInfo
  }

  const getTaskDetail = async () => {
    const res: any = await getTaskById({ id: props.info.id })
    if (res) {
      detailInfo.value = res?.data || {}
      form.value.employer = res.data?.employer || {}
      form.value.verifyerList = res.data?.verifyerList || []
    }
  }

  onMounted(async () => {
    if (props.type != 'add') await getTaskDetail()
    await getServiceProviderList()
    await getUserList()
    if (props.type == 'add') setEmployer()
    setInfo(detailInfo.value)
  })

  defineExpose({ resetServiceInfo, getForm })
</script>

<style lang="less" scoped>
  .mt20 {
    margin-top: 20px;
  }

  .sel-item-detail.right {
    padding-left: 20px;
    img {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      overflow: hidden;
    }
  }

  .sample-address {
    width: 100%;
    .address-con {
      width: 100%;
      min-height: 40px;
      padding: 10px;
      border: 1px solid #e7e7e7;
      border-radius: 5px;
    }
  }

  .current-page-common-text {
    color: #d3d3d3;
    font-size: 15px;
  }

  .sel-item-detail {
    width: 50%;
    min-height: 650px;
    padding: 10px 20px 10px 0;
    &:nth-child(1) {
      border-right: 1px solid #d3d3d3;
    }
  }

  .service-com-short-description {
    width: 100%;
    height: 60px;
    background-color: #fbf3ed;
    border-radius: 10px;
    padding: 0 5px;
    box-sizing: border-box;
    img {
      width: 20px;
      height: 20px;
      border-radius: 50%;
      overflow: hidden;
    }
    .line {
      width: 2px;
      height: 14px;
      background-color: #eddfd2;
    }
    .base-text-color {
      color: #b77b07;
    }
  }

  .sample-con {
    display: inline-block;
    width: 20px;
    height: 20px;
    text-align: center;
    line-height: 20px;
    color: white;
    border-radius: 50%;
    background-color: #6bb900;
    margin-left: 5px;
  }

  .left-text {
    display: inline-block;
    width: 85px;
  }

  .ser-Content {
    width: 150px;
    font-size: 16px;
    font-weight: 700;
  }

  .mt5 {
    margin-top: 5px;
  }

  .fs12 {
    font-size: 12px;
  }

  .tab-detail-con {
    // padding: 5px;
    .sku-info {
      padding: 5px;
      border: 1px solid #d7d7d7;
      border-radius: 5px;
      min-height: 72px;
      .sku-detail-con {
        position: relative;
        // min-height: 72px;
        .del-btn {
          position: absolute;
          right: 10px;
          top: 10px;
        }
      }
    }
    .service-provide-con {
      width: 100%;
      box-sizing: border-box;
      .provider-item-con {
        white-space: nowarp;
        display: inline-flex;
        .item {
          font-size: 12px;
          // width: 160px;
          margin-right: 10px;
          padding: 5px 10px;
          border: 1px solid #d7d7d7;
          background-color: white;
          text-align: center;
          border-radius: 20px;
        }
        .active {
          color: white;
          background-color: #165dff;
        }
      }
    }
    .service-provider-statics {
      border: 1px solid #d7d7d7;
      border-radius: 5px;
      padding: 5px 10px;
      font-size: 12px;
    }
    .service-item-list-con {
      .service-goods-con {
        display: flex;
        flex-wrap: wrap;
      }
      .service-goods {
        width: 280px;
        height: 220px;
        // border: 1px solid #e5e6eb;
        background: white;
        border-radius: 5px;
        padding: 5px;
        font-size: 12px;
        position: relative;
        .footer {
          position: absolute;
          bottom: 7px;
        }
      }
    }
  }

  .com-address-statics {
    display: flex;
    margin-top: 10px;
    .statstics {
      width: 100px;
      border: 1px solid #d7d7d7;
      padding: 5px;
      font-size: 12px;
    }
    .address {
      flex: 1;
      padding: 5px;
      font-size: 12px;
      margin-left: 10px;
      border: 1px solid #d7d7d7;
    }
  }

  .att-list-con {
    margin-top: 5px;
    .att-item {
      width: 100%;
      font-size: 12px;
      background-color: #d7d7d7;
      padding: 5px 10px;
      border-radius: 3px;
      margin-bottom: 8px;
    }
  }

  .sel-template {
    width: 100%;
    min-height: 100px;
    // border: 1px solid #d7d7d7;
    border-radius: 5px;
    // margin-top: 20px;
    padding: 5px;
    display: flex;
    flex-wrap: wrap;
    .item {
      width: 180px;
      height: 140px;
      margin-right: 10px;
      .top {
        width: 180px;
        height: 100px;
      }
    }
  }

  .product-img-box {
    overflow: hidden;
    .box {
      margin-top: 5px;
      // min-height: 180px;
      // border-right: 1px solid #d7d7d7;
      .box-img-con {
        float: left;
        width: 80px;
        height: 80px;
        position: relative;
        margin: 0 10px 10px 0;
        &:hover {
          .mask {
            display: block;
          }
        }
        .mask {
          height: 80px;
          width: 80px;
          position: absolute;
          top: 0;
          left: 0;
          display: none;
          z-index: 1;
          background: rgba(0, 0, 0, 0.5);
          .btn-con {
            width: 80px;
            color: white;
            font-size: 18px;
            text-align: center;
            margin-top: 25px;
            align-items: center;
          }
        }
      }
    }
  }
</style>
